import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:file_picker/file_picker.dart';
import 'profile_state.dart';
import '../../data/services/storage_service.dart';
import '../../data/services/preferences_service.dart';

/// 我的页面逻辑控制器 - Profile Logic Controller
/// 
/// 管理我的页面的业务逻辑和状态更新
/// Manages business logic and state updates for the profile page
class ProfileLogic extends GetxController {
  /// 状态实例 - State instance
  /// Contains all state variables for the profile page
  final ProfileState state = ProfileState();

  /// 存储服务 - Storage service
  /// Service for handling local storage operations
  final StorageService _storageService = Get.find<StorageService>();

  /// 文件系统服务 - File system service
  /// Service for handling file system operations
  // final FileSystemService _fileSystemService = Get.find<FileSystemService>();

  /// 偏好设置服务 - Preferences service
  /// Service for handling key-value pair preferences
  final PreferencesService _preferencesService = Get.find<PreferencesService>();

  @override
  void onInit() {
    super.onInit();
    _initializeProfile();
  }

  /// 初始化个人资料 - Initialize Profile
  /// Loads user settings and preferences from storage
  /// 从存储中加载用户设置和偏好
  Future<void> _initializeProfile() async {
    try {
      state.isLoading = true;
      update();

      // 加载用户设置 - Load user settings
      await _loadUserSettings();
      
      // 设置默认存储路径 - Set default storage path
      await _setDefaultStoragePath();

    } catch (e) {
      state.errorMessage = '初始化失败: $e';
    } finally {
      state.isLoading = false;
      update();
    }
  }

  /// 加载用户设置 - Load User Settings
  /// Retrieves user preferences from local storage
  /// 从本地存储检索用户偏好设置
  Future<void> _loadUserSettings() async {
    // 加载语言设置 - Load language setting
    state.language = await _preferencesService.getString('language') ?? 'zh-CN';
    
    // 加载默认格式 - Load default format
    state.defaultFormat = await _preferencesService.getString('defaultFormat') ?? 'md';
    
    // 加载自动保存设置 - Load auto save setting
    state.autoSave = await _preferencesService.getBool('autoSave') ?? true;
    
    // 加载自动备份设置 - Load auto backup setting
    state.autoBackup = await _preferencesService.getBool('autoBackup') ?? true;
    
    // 加载存储路径 - Load storage path
    state.storagePath = await _preferencesService.getString('storagePath') ?? '';
    
    // 加载自定义存储路径 - Load custom storage path
    state.customStoragePath = await _preferencesService.getString('customStoragePath') ?? '';
  }

  /// 设置默认存储路径 - Set Default Storage Path
  /// Sets platform-specific default storage paths
  /// 设置平台特定的默认存储路径
  Future<void> _setDefaultStoragePath() async {
    if (state.storagePath.isEmpty) {
      String defaultPath;
      
      if (Platform.isAndroid) {
        // Android默认路径：内部存储空间/Prompt/PromptFlie
        final directory = await getExternalStorageDirectory();
        defaultPath = '${directory?.path}/Prompt/PromptFlie';
      } else if (Platform.isWindows) {
        // Windows默认路径：C:\Users\Administrator\Documents\PromptFlie
        defaultPath = r'C:\Users\Administrator\Documents\PromptFlie';
      } else {
        // 其他平台使用应用文档目录
        final directory = await getApplicationDocumentsDirectory();
        defaultPath = '${directory.path}/PromptFlie';
      }
      
      state.storagePath = defaultPath;
      await _preferencesService.setString('storagePath', defaultPath);
      
      // 创建目录 - Create directory
      await _createStorageDirectories(defaultPath);
    }
  }

  /// 创建存储目录 - Create Storage Directories
  /// Creates the main and backup storage directories
  /// 创建主存储目录和备份目录
  Future<void> _createStorageDirectories(String basePath) async {
    try {
      // 创建主目录 - Create main directory
      final mainDir = Directory(basePath);
      if (!await mainDir.exists()) {
        await mainDir.create(recursive: true);
      }
      
      // 创建备份目录 - Create backup directory
      final backupDir = Directory('$basePath.old');
      if (!await backupDir.exists()) {
        await backupDir.create(recursive: true);
      }
    } catch (e) {
      // print('创建存储目录失败: $e');
      Get.log('创建存储目录失败: $e');
    }
  }

  /// 显示语言选择对话框 - Show Language Selection Dialog
  /// Displays dialog for language preference selection
  /// 显示语言偏好选择对话框
  void showLanguageDialog() {
    Get.dialog(
      AlertDialog(
        title: const Text('选择语言'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              title: const Text('中文'),
              leading: Radio<String>(
                value: 'zh-CN',
                groupValue: state.language,
                onChanged: (value) {
                  if (value != null) {
                    setLanguage(value);
                    Get.back();
                  }
                },
              ),
            ),
            ListTile(
              title: const Text('English'),
              leading: Radio<String>(
                value: 'en-US',
                groupValue: state.language,
                onChanged: (value) {
                  if (value != null) {
                    setLanguage(value);
                    Get.back();
                  }
                },
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  /// 设置语言 - Set Language
  /// Updates the application language preference
  /// 更新应用程序语言偏好
  Future<void> setLanguage(String language) async {
    state.language = language;
    await _preferencesService.setString('language', language);
    update();
    
    // 更新应用语言 - Update app language
    if (language == 'zh-CN') {
      Get.updateLocale(const Locale('zh', 'CN'));
    } else {
      Get.updateLocale(const Locale('en', 'US'));
    }
  }

  /// 显示格式选择对话框 - Show Format Selection Dialog
  /// Displays dialog for default document format selection
  /// 显示默认文档格式选择对话框
  void showFormatDialog() {
    Get.dialog(
      AlertDialog(
        title: const Text('选择默认格式'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              title: const Text('Markdown (.md)'),
              leading: Radio<String>(
                value: 'md',
                groupValue: state.defaultFormat,
                onChanged: (value) {
                  if (value != null) {
                    setDefaultFormat(value);
                    Get.back();
                  }
                },
              ),
            ),
            ListTile(
              title: const Text('文本文件 (.txt)'),
              leading: Radio<String>(
                value: 'txt',
                groupValue: state.defaultFormat,
                onChanged: (value) {
                  if (value != null) {
                    setDefaultFormat(value);
                    Get.back();
                  }
                },
              ),
            ),
            ListTile(
              title: const Text('Word文档 (.doc)'),
              leading: Radio<String>(
                value: 'doc',
                groupValue: state.defaultFormat,
                onChanged: (value) {
                  if (value != null) {
                    setDefaultFormat(value);
                    Get.back();
                  }
                },
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  /// 设置默认格式 - Set Default Format
  /// Updates the default document format preference
  /// 更新默认文档格式偏好
  Future<void> setDefaultFormat(String format) async {
    state.defaultFormat = format;
    await _preferencesService.setString('defaultFormat', format);
    update();
  }

  /// 切换自动保存 - Toggle Auto Save
  /// Toggles the automatic save preference
  /// 切换自动保存偏好
  Future<void> toggleAutoSave(bool value) async {
    state.autoSave = value;
    await _preferencesService.setBool('autoSave', value);
    update();
  }

  /// 显示存储位置对话框 - Show Storage Location Dialog
  /// Displays dialog for custom storage path selection with manual input and folder picker
  /// 显示自定义存储路径选择对话框，支持手动输入和文件夹选择
  void showStorageDialog() {
    final TextEditingController pathController = TextEditingController(text: state.storagePath);
    
    Get.dialog(
      AlertDialog(
        title: const Text('设置存储位置'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: pathController,
              decoration: const InputDecoration(
                labelText: '存储路径',
                hintText: '请输入自定义存储路径',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 12),
            // 文件夹选择按钮 - Folder picker button
            SizedBox(
              width: double.infinity,
              child: OutlinedButton.icon(
                onPressed: () async {
                  // 使用文件夹选择器 - Use folder picker
                  String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
                  if (selectedDirectory != null) {
                    pathController.text = selectedDirectory;
                  }
                },
                icon: const Icon(Icons.folder_open),
                label: const Text('选择文件夹'),
              ),
            ),
            const SizedBox(height: 16),
            const Text(
              '注意：更改存储位置后，需要重新启动应用才能生效',
              style: TextStyle(fontSize: 12, color: Colors.grey),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              final newPath = pathController.text.trim();
              if (newPath.isNotEmpty) {
                await setStoragePath(newPath);
                Get.back();
              }
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 设置存储路径 - Set Storage Path
  /// Updates the custom storage path
  /// 更新自定义存储路径
  Future<void> setStoragePath(String path) async {
    try {
      // 创建新的存储目录 - Create new storage directories
      await _createStorageDirectories(path);
      
      state.storagePath = path;
      await _preferencesService.setString('storagePath', path);
      update();
      
      Get.snackbar(
        '设置成功',
        '存储路径已更新，请重启应用以生效',
        snackPosition: SnackPosition.BOTTOM,
      );
    } catch (e) {
      Get.snackbar(
        '设置失败',
        '无法创建存储目录: $e',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    }
  }

  /// 切换自动备份 - Toggle Auto Backup
  /// Toggles the automatic backup preference
  /// 切换自动备份偏好
  Future<void> toggleAutoBackup(bool value) async {
    state.autoBackup = value;
    await _preferencesService.setBool('autoBackup', value);
    
    // 同时更新存储服务中的自动备份设置 - Also update auto backup setting in storage service
    await _storageService.setAutoBackupEnabled(value);
    
    update();
  }

  /// 显示关于对话框 - Show About Dialog
  /// Displays application information dialog
  /// 显示应用程序信息对话框
  void showAboutDialog() {
    Get.dialog(
      AlertDialog(
        title: const Text('关于 Prompt Manager'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('版本: ${state.appVersion}'),
            const SizedBox(height: 8),
            const Text('一款专业的 Prompt 管理工具'),
            const SizedBox(height: 8),
            const Text('支持本地存储、版本管理和富文本编辑'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 显示帮助对话框 - Show Help Dialog
  /// Displays help and support information
  /// 显示帮助和支持信息
  void showHelpDialog() {
    Get.dialog(
      AlertDialog(
        title: const Text('帮助与支持'),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('使用指南:'),
            Text('• 点击 + 按钮创建新的 Prompt'),
            Text('• 长按 Prompt 卡片进入选择模式'),
            Text('• 使用搜索和筛选功能快速查找'),
            SizedBox(height: 16),
            Text('常见问题:'),
            Text('• 如何备份数据？在设置中开启自动备份'),
            Text('• 如何更改存储位置？在存储设置中自定义路径'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 导航到设置页面 - Navigate to Settings Page
  /// Opens the settings page (legacy support)
  /// 打开设置页面（遗留支持）
  void navigateToSettings() {
    // 由于设置功能已迁移到我的页面，这里可以显示提示或直接在当前页面处理
    Get.snackbar(
      '提示',
      '设置功能已集成到当前页面',
      snackPosition: SnackPosition.BOTTOM,
    );
  }

  /// 导航到登录页面 - Navigate to Login Page
  /// Opens the login page (future functionality)
  /// 打开登录页面（未来功能）
  void navigateToLogin() {
    Get.snackbar(
      '提示',
      '此功能暂未开放',
      snackPosition: SnackPosition.BOTTOM,
    );
  }

  /// 显示自定义存储路径对话框 - Show Custom Storage Path Dialog
  /// Displays dialog for setting custom storage location with manual input and folder picker
  /// 显示设置自定义存储位置的对话框，支持手动输入和文件夹选择
  void showCustomStorageDialog() {
    final TextEditingController pathController = TextEditingController(text: state.customStoragePath);
    
    Get.dialog(
      AlertDialog(
        title: const Text('设置自定义存储路径'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: pathController,
              decoration: const InputDecoration(
                labelText: '自定义存储路径',
                hintText: '留空使用默认路径',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 12),
            // 文件夹选择按钮 - Folder picker button
            SizedBox(
              width: double.infinity,
              child: OutlinedButton.icon(
                onPressed: () async {
                  // 使用文件夹选择器 - Use folder picker
                  String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
                  if (selectedDirectory != null) {
                    pathController.text = selectedDirectory;
                  }
                },
                icon: const Icon(Icons.folder_open),
                label: const Text('选择文件夹'),
              ),
            ),
            const SizedBox(height: 16),
            const Text(
              '自定义路径将覆盖默认存储位置\n留空则使用系统默认路径',
              style: TextStyle(fontSize: 12, color: Colors.grey),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              final newPath = pathController.text.trim();
              await setCustomStoragePath(newPath);
              Get.back();
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 设置自定义存储路径 - Set Custom Storage Path
  /// Updates the custom storage path and applies it to storage service
  /// 更新自定义存储路径并应用到存储服务
  Future<void> setCustomStoragePath(String path) async {
    try {
      state.customStoragePath = path;
      await _preferencesService.setString('customStoragePath', path);
      
      if (path.isNotEmpty) {
        // 设置自定义存储路径到存储服务 - Set custom storage path to storage service
        final success = await _storageService.setCustomStoragePath(path);
        if (success) {
          Get.snackbar(
            '设置成功',
            '自定义存储路径已更新',
            snackPosition: SnackPosition.BOTTOM,
          );
        } else {
          Get.snackbar(
            '设置失败',
            '无法设置自定义存储路径',
            snackPosition: SnackPosition.BOTTOM,
            backgroundColor: Colors.red,
            colorText: Colors.white,
          );
        }
      } else {
        Get.snackbar(
          '设置成功',
          '已恢复使用默认存储路径',
          snackPosition: SnackPosition.BOTTOM,
        );
      }
      
      update();
    } catch (e) {
      Get.snackbar(
        '设置失败',
        '设置自定义存储路径时出错: $e',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    }
  }

  /// 刷新页面数据 - Refresh Page Data
  /// Reloads all profile data and settings
  /// 重新加载所有个人资料数据和设置
  Future<void> refreshData() async {
    await _initializeProfile();
  }
}